package com.example.springboot.controller;

import com.example.springboot.utils.VoteSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.URLDecoder;

/**
 * 在线投票结果页面-动态刷新数据
 *
 * @author wenlinyu
 */
@ServerEndpoint("/api/websocket/{voteId}")
@Component
public class VoteServerEndpoint {

    private static final Logger log = LoggerFactory.getLogger(VoteServerEndpoint.class);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("voteId") String voteId) {
        try {
            VoteSocketUtils.put(voteId, session);
            log.info("有新连接加入！voteId: {}", voteId);
        } catch (Exception e) {
            log.error(String.format("操作异常; 错误码：%s, 错误信息：%s", 500, e.getMessage()));
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(@PathParam("voteId") String voteId, Session session) {
        VoteSocketUtils.remove(voteId, session);
        log.info("有一连接关闭！voteId: {}", voteId);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session, @PathParam("voteId") String voteId) {
        if (message.contains("ping")) {
            System.out.println("客户端心跳连接！");
            return;
        }
        log.info("来自客户端的消息========= voteId: {}, message: {}", voteId, message);
        try {
            message = URLDecoder.decode(message, "UTF-8");
            VoteSocketUtils.sendMessageAll(voteId, message);
        } catch (Exception e) {
            log.error("onMessage error: {}", e);
        }
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        try {
            session.close();
        } catch (IOException e) {
            log.error("onError error: {}", e);
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendMessageAll(String message, @PathParam("voteId") String voteId) {
        log.info("========================sendMessageAll, voteId: {}, message==", voteId, message);
        try {
            VoteSocketUtils.sendMessageAll(voteId, message);
        } catch (IOException e) {
            log.error("sendMessageAll error: {}", e);
        }

    }

}
